<?php

namespace App\Http\Controllers\Site\Custom\Purchaser;

use App\B2BProject\Custom\AuthorizationRequest;
use App\B2BProject\Site\HelperControllerBuildTrait;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;

class MyAuthorizationRequestController extends Controller
{
    use HelperControllerBuildTrait;

    public function getIndex(Request $request)
    {
        $request->query->set('page', $request->query('page', $request->page));
        $pageSize = $request->query('pageSize', $request->pageSize);

        if ($request->ajax()) {
            $authorizationRequests = \Auth::user()->purchaserAuthorizationRequests();

            if ($start = $request->query('startTime')) {
                $authorizationRequests->where('created_at', '>=', date('Y-m-d', strtotime($start)));
            }

            if ($end = $request->query('endTime')) {
                $authorizationRequests->where('created_at', '<=', date('Y-m-d', strtotime($end)));
            }

            if ($provider = $request->query('supplyName')) {
                $authorizationRequests->whereHas('provider.information', function(Builder $builder) use ($provider) {
                    $builder->where('company', 'like', "%$provider%");
                });
            }

            $authorizationRequests = $authorizationRequests->paginate($pageSize);

            $data = [
                'pagingConfData' => [
                    'page'     => $request->page,
                    'pageSize' => $pageSize,
                    'total'    => $authorizationRequests->total(),
                ],
            ];

            foreach ($authorizationRequests as $authorizationRequest) {
                $data['data'][] = [
                    'id'        => $authorizationRequest->id,
                    'goodsname' => $authorizationRequest->provider->information->company,
                    'time'      => date('Y-m-d', strtotime($authorizationRequest->created_at)),
                    'state'     => [1, 0, 2, 3][$authorizationRequest->status],
                ];
            }

            return response()->json($data);
        }

        return view('host/custom/purchaser/my-authorization-request/index');
    }

    /**
     * 终止授权
     *
     * @param Request $request
     *
     * @return \Illuminate\Http\JsonResponse|\Illuminate\View\View
     */
    public function putIndex(Request $request)
    {
        if ($request->ajax()) {
            $id = $request->id;

            $authorizationReuqest
                = \Auth::user()->purchaserAuthorizationRequests()->pending()->whereId($id)->firstOrFail();

            $authorizationReuqest->status = 3;

            $authorizationReuqest->save();

            return $this->getIndex($request);
        }
    }
}
